import functools

from flask import Blueprint
from flask import render_template
from flask import request
from flask import session
from flask import redirect
from flask import url_for
from flask import flash
from flask import g

from src.dao.user_dao import search_user
from src.dao.user_dao import create_user
from src.dao.user_dao import get_user

bp = Blueprint("auth", __name__, url_prefix="/auth", template_folder="templates", static_folder="static")


def login_verification(view):
    """登陆权限验证装饰器"""
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for("auth.login"))
        return view(**kwargs)
    return wrapped_view


@bp.before_app_request
def load_logged_in_user():
    # 每次请求前都会去session中查看user_id来获取用户
    user_id = session.get("user_id")
    if user_id is None:
        g.user = None
    else:
        g.user = get_user(user_id)


@bp.route("/login", methods=["GET", "POST"])
def login():
    """登录视图"""
    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        if username == "" and password == "":
            flash("账号或密码不能为空")
            return redirect(url_for("auth.login"))
        data = {"username": username}
        print(data)
        result = search_user(data)
        error = None
        if result is None:
            error = "用户不存在"
        else:
            if hasattr(result, "username"):
                if result.password != password:
                    error = "密码错误"
            else:
                error = result
        if error is None:
            session.clear()
            session["user_id"] = result.id
            return redirect(url_for('index'))
        else:
            flash(error)
            return render_template("/auth/login.html", error=error)
    elif request.method == "GET":
        return render_template("/auth/login.html")


@bp.route("/register", methods=["GET", "POST"])
def register():
    """注册视图"""
    if request.method == "POST":
        form = request.form.to_dict()
        print(form)
        username = request.form.get("username")
        password = request.form.get("password")
        data = {"username": username}
        exists_user = search_user(data)
        if username == "" and password == "":
            flash("账号或密码不能为空")
            return redirect(url_for("auth.register"))
        if exists_user:
            flash(f"{username}用户名已存在，请更换其他用户名")
            return redirect(url_for("auth.register"))
        else:
            user = create_user(data)
            session.clear()
            session["user_id"] = user.id
            flash("注册成功")
            return redirect("/auth/login")
    return render_template("/auth/register.html")


@login_verification
@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("auth.login"))
